﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace Ant.ICommon.Extensions
{
    public static class DictionaryExtensions
    {
        public static T GetValue<TKey, T>(this IDictionary<TKey, object> dict, object key)
        {
            return GetValue<T>(dict as IDictionary, key);
        }

        public static T GetValueOrDefault<TKey, T>(this IDictionary<TKey, object> dict, object key, T def = default(T))
        {
            return GetValueOrDefault(dict as IDictionary, key, def);
        }

        public static T GetValueIsNullOrDefault<TKey, T>(this IDictionary<TKey, object> dict, object key, T def = default(T))
        {
            return GetValueIsNullOrDefault(dict as IDictionary, key, def);
        }

        public static T GetValue<T>(this IDictionary dict, object key)
        {
            if (key == null)
                throw new ArgumentNullException("key");
            if (!dict.Contains(key))
                throw new Exception(string.Format("字典中不存在Key{0}。", key));
            return (T)dict[key];
        }

        public static T GetValueOrDefault<T>(this IDictionary dict, object key, T def = default(T))
        {
            if (key == null)
                throw new ArgumentNullException("key");
            if (!dict.Contains(key))
                return def;
            try
            {
                return (T)dict[key];
            }
            catch
            {
                return def;
            }
        }

        public static T GetValueIsNullOrDefault<T>(this IDictionary dict, object key, T def = default(T))
        {
            if (key == null)
                throw new ArgumentNullException("key");
            if (!dict.Contains(key))
                return def;
            try
            {
                var result = (T)dict[key];
                if (result == null)
                    return def;
                return result;
            }
            catch
            {
                return def;
            }
        }
    }
}